import type {ApiConfig, SearchField, TableColumn, TableConfig} from '@/components/base/CommonTable/types'
import {datasourceApi, type DatasourceDTO} from '@/api/codegen'
import type {FormField} from '@/components/base/CommonForm/types'

// 自定义校验函数
const validateDatasourceName = async (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请输入数据源名称'))
    return
  }
  if (value.length > 100) {
    callback(new Error('数据源名称长度不能超过100个字符'))
    return
  }
  callback()
}

const validateUrl = async (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请输入数据库连接URL'))
    return
  }
  if (!value.startsWith('jdbc:')) {
    callback(new Error('数据库连接URL格式不正确，应以jdbc:开头'))
    return
  }
  callback()
}

const validateHost = async (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请输入主机地址'))
    return
  }
  callback()
}

const validatePort = async (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请输入端口号'))
    return
  }
  if (value < 1 || value > 65535) {
    callback(new Error('端口号必须在1-65535之间'))
    return
  }
  callback()
}

// 表单字段配置
export const getFormFields = (isEdit: boolean = false, autoGenerateUrl: boolean = true): FormField[] => {
  return [
    {
      prop: 'name',
      label: '数据源名称',
      type: 'input',
      required: true,
      maxlength: 100,
      showWordLimit: true,
      rules: [
        { validator: validateDatasourceName, trigger: 'blur' }
      ]
    },
    {
      prop: 'dbType',
      label: '数据库类型',
      type: 'select',
      required: true,
      options: [
        { label: 'MySQL', value: 'mysql' },
        { label: 'SQL Server', value: 'sqlserver' },
        { label: 'PostgreSQL', value: 'postgresql' },
        { label: 'Oracle', value: 'oracle' }
      ],
      rules: [
        { required: true, message: '请选择数据库类型', trigger: 'change' }
      ]
    },
    {
      prop: 'host',
      label: '主机地址',
      type: 'input',
      required: true,
      placeholder: '请输入主机地址，如：localhost',
      rules: [
        { validator: validateHost, trigger: 'blur' }
      ]
    },
    {
      prop: 'port',
      label: '端口',
      type: 'number',
      required: true,
      min: 1,
      max: 65535,
      rules: [
        { validator: validatePort, trigger: 'blur' }
      ]
    },
    {
      prop: 'databaseName',
      label: '数据库名',
      type: 'input',
      required: true,
      placeholder: '请输入数据库名称',
      rules: [
        { required: true, message: '请输入数据库名称', trigger: 'blur' }
      ]
    },
    {
      prop: 'username',
      label: '用户名',
      type: 'input',
      required: true,
      placeholder: '请输入数据库用户名',
      rules: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ]
    },
    {
      prop: 'password',
      label: '密码',
      type: 'password',
      required: true,
      placeholder: '请输入数据库密码',
      showPassword: true,
      rules: [
        { required: true, message: '请输入密码', trigger: 'blur' }
      ]
    },
    {
      prop: 'url',
      label: '连接URL',
      type: 'slot',
      required: true,
      rows: 3,
      placeholder: autoGenerateUrl ? '将根据数据库类型、主机、端口、数据库名自动生成' : '请手动输入数据库连接URL',
      readonly: false,
      rules: [
        { validator: validateUrl, trigger: 'blur' }
      ],
    },
    {
      prop: 'status',
      label: '状态',
      type: 'switch',
      activeText: '启用',
      inactiveText: '禁用',
      activeValue: 1,
      inactiveValue: 0
    },
    {
      prop: 'remark',
      label: '备注',
      type: 'textarea',
      rows: 3,
      placeholder: '请输入备注信息'
    }
  ]
}

// 表格列配置
export const getTableColumns = (): TableColumn[] => [
  {
    prop: 'id',
    label: 'ID',
    width: 80,
    sortable: true
  },
  {
    prop: 'name',
    label: '数据源名称',
    width: 150,
    sortable: true
  },
  {
    prop: 'dbType',
    label: '数据库类型',
    width: 120,
    formatter: (row: any) => {
      const typeMap: Record<string, string> = {
        mysql: 'MySQL',
        sqlserver: 'SQL Server',
        postgresql: 'PostgreSQL',
        oracle: 'Oracle'
      }
      return typeMap[row.dbType] || row.dbType
    }
  },
  {
    prop: 'host',
    label: '主机',
    width: 120
  },
  {
    prop: 'port',
    label: '端口',
    width: 80
  },
  {
    prop: 'databaseName',
    label: '数据库',
    width: 120
  },
  {
    prop: 'username',
    label: '用户名',
    width: 100
  },
  {
    prop: 'status',
    label: '状态',
    width: 80,
    formatter: (row: any) => {
      return row.status === 1 ? '启用' : '禁用'
    }
  },
  {
    prop: 'remark',
    label: '备注',
    minWidth: 150,
    showOverflowTooltip: true
  }
]

// 表格搜索字段配置
export const getSearchFields = (): SearchField[] => [
  {
    key: 'name',
    label: '数据源名称',
    type: 'text'
  },
  {
    key: 'dbType',
    label: '数据库类型',
    type: 'select',
    options: [
      { label: 'MySQL', value: 'mysql' },
      { label: 'SQL Server', value: 'sqlserver' },
      { label: 'PostgreSQL', value: 'postgresql' },
      { label: 'Oracle', value: 'oracle' }
    ]
  },
  {
    key: 'host',
    label: '主机',
    type: 'text'
  },
  {
    key: 'port',
    label: '端口',
    type: 'number'
  },
  {
    key: 'status',
    label: '状态',
    type: 'select',
    options: [
      { label: '启用', value: 1 },
      { label: '禁用', value: 0 }
    ]
  }
]

// 表格配置
export const getTableConfig = (): TableConfig => ({
  title: '数据源管理',
  description: '管理系统中的数据源配置信息',
  showHeader: true,
  showSearch: true,
  showPagination: true,
  showSelection: true,
  showIndex: true,
  showActions: true,
  showAddButton: true,
  addButtonText: '新增数据源',
  showEditButton: true,
  showDeleteButton: true,
  stripe: true,
  border: true,
  actionWidth: 250,
  actionFixed: 'right',
  pageSizes: [10, 20, 50, 100],
  paginationLayout: 'total, sizes, prev, pager, next, jumper',
  searchFields: getSearchFields()
})

// API配置
export const getApiConfig = (): ApiConfig => ({
  listApi: datasourceApi.page,
  deleteApi: datasourceApi.delete
})

// 业务操作API
export const TableApis = {
  createDatasource: datasourceApi.create,
  updateDatasource: datasourceApi.update,
  deleteDatasource: datasourceApi.delete,
  testConnection: datasourceApi.testConnection
}